import util from './util.js';
import authLogin from './autuLogin.js';
import sdk from './sdk.js';
import CONFIG from './../config.js';
/**
 * 发送请求
 */
export default function request(api, method, data, {noAuth = true, noVerify = false})
{
  if (!noAuth) {
    //登录过期自动登录
    if (!util.checkLogin()) return authLogin().then(res => { return request(api, method, data, { noAuth, noVerify}); });
  }
  if (CONFIG.IS_GATEWAY) {
    return gatewayRequest(api, data, noVerify);
  } else {
    return apiRequest(api, method, data, noVerify);
  }
} 

['options', 'get', 'post', 'put','connect'].forEach((method) => {
  request[method] = (api, data, opt) => request(api, method, data, opt || {})
});

/** api请求 */
const apiRequest = function (api, method, data, noVerify) {
  var header = CONFIG.HEADER;
  // 添加token验证
  if (getApp().globalData.token) {
    header[CONFIG.TOKENNAME] = 'Bearer ' + getApp().globalData.token;
  }
  var promise = new Promise((reslove, reject) => {
    wx.request({
      url: CONFIG.HTTP_REQUEST_URL + '/' + api + '/',
      method: method || 'GET',
      header: header,
      data: data || {},
      success: (res) => {
        //return reslove(res.data, res);
        // http请求不成功
        if (res.statusCode != 200) {
          return reject(res.errMsg);
        }
        if (noVerify || ! res.data.sub_code) {
          return reslove(res.data, res);
        }
        // 需要重新登陆处理
        if ([400000].indexOf(res.data.sub_code) !== -1) {
          util.logout()
          return authLogin().then(res => { return request(api, method, data, { noAuth, noVerify }); });
        } 
        reject(res.data.sub_msg);
      },
      fail: (msg) => {
        console.log(msg);
        reject('请求失败');
      }
    })
  });
  return promise;
}

/** 走网关请求 */
const gatewayRequest = function (api, data, noVerify) {
  var data_ = data || {};
  // 如果是网关请求，处理数据
  var datastr = JSON.stringify(data_);
  var params = {
    app_id: CONFIG.GATEWAY_APPID,
    version: CONFIG.API_VERSION,
    charset: 'utf-8',
    format: 'json',
    timestamp: sdk.formatDate(new Date()),
    method: api,
    data: datastr
  };
  //console.log('----------------------------')
  //console.log(getApp().globalData);
  // 添加token验证
  if (getApp().globalData.token) {
    params.token = getApp().globalData.token;
  }
  params.sign = sdk.buildSign(params, CONFIG.GATEWAY_APPSECRET);
  console.log('网关请求参数: ');
  console.log(params);
  return new Promise((reslove, reject) => {
    wx.request({
      url: CONFIG.GATEWAY_REQUEST_URL,
      method: 'POST',
      header: CONFIG.HEADER,
      data: params,
      success: (res) => {
        // http请求不成功
        if (res.statusCode != 200) {
          return reject(res.errMsg);
        }
        var response_ = res.data.response;
        // 业务请求成功
        if (noVerify || response_.code == 10000) {
          var data_ = response_.data.items || response_.data;
          return reslove(data_, res);
        }
        // 需要登陆处理
        if ([400000].indexOf(response_.code) !== -1) {
          util.logout()
          return authLogin().then(res => { return request(api, method, data, { noAuth, noVerify }); });
        }
        if (response_.data) {
          reject(response_.data.sub_msg);
        } else {
          reject(response_.msg);
        }
        
      },
      fail: (msg) => {
        console.log(msg);
        reject('请求失败');
      }
    })
  });
}

